package filewriting;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import commonfunctions.Matrix;

/**
 * This is the class that uses the user-created PruningAlgorithm class. Creates a two dimensional array of 
 * booleans where entry (i, j) is true if observation j is the first observation after i corresponding to 
 * an object.
 * 
 * @author Trevor Terris
 *
 */
public class PruneGraphWriter 
{
	public static final String PRUNED_GRAPH_NAME = "pruned-graph.txt";

	public static Thread startWriting(Matrix tracks, String dirName)
	{
		Thread toReturn = new WritingThread(tracks, dirName);
		toReturn.start();
		return toReturn;
	}
	
	private static class WritingThread extends Thread
	{
		private String myDirName;
		private Matrix myTracks;
		public WritingThread(Matrix tracks, String dirName)
		{
			myTracks = tracks;
			myDirName = dirName;
		}
		public void run()
		{
			try
			{	
				Matrix toWrite = new Matrix(myTracks);
				
				File f = new File(myDirName + "/" + PRUNED_GRAPH_NAME);
				
		        Writer output = null;
		        output = new BufferedWriter(new FileWriter(f));
		        output.flush();
		        
		        output.write("Lines: " + toWrite.length() + "\n");
		        
		        for (int k = 0; k < toWrite.length(); k++)
		        {
		        	for (int j = 0; j < toWrite.length(); j++)
		        	{
		        		if (toWrite.getBoolean(k, j))
		        		{
		        			output.write("" + j);
		        			break;
		        		}
		        	}
		    		if (k != toWrite.length() - 1)
		    			output.write("\n");
		        }
		        
		        output.close();
			}
			catch (IOException e)
			{
				System.out.println("Problem writing to file.");
			}
		}
	}
}
